package main

import (
	"net"
	"strings"
)

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	server *Server
}

//1.创建一个用户的API
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name: userAddr,
		Addr: userAddr,
		C:    make(chan string),
		conn: conn,

		server: server,
	}

	//启动go程来监听user channel的消息
	go user.ListenMessage()
	return user
}

//2,监听当前User channel的方法 一有消息就发送给对端客户端
func (u *User) ListenMessage() {
	for {
		msg := <-u.C
		u.conn.Write([]byte(msg + "\n"))
	}
}

//3.用户上线功能
func (u *User) Online() {
	//用户上线就加入onlinMap
	u.server.mapLock.Lock()
	u.server.OnlineMap[u.Name] = u
	u.server.mapLock.Unlock()

	//广播当前用户上线消息
	u.server.BroadCast(u, " UP!!!")
}

//4.用户下线功能
func (u *User) Offline() {
	//用户下线onlinMap中删除
	u.server.mapLock.Lock()
	delete(u.server.OnlineMap, u.Name)
	u.server.mapLock.Unlock()

	//广播用户下线消息
	u.server.BroadCast(u, " DOWN!!!")

}

//5.用户处理消息
func (u *User) DoMessage(msg string) {
	if msg == "who" {
		//查询当前用户
		u.server.mapLock.Lock()
		for _, user := range u.server.OnlineMap {
			onlineMsg := "[" + user.Addr + "]" + user.Name + ":" + "在线~\n"
			u.SendMsg(onlineMsg)
		}
		u.server.mapLock.Unlock()
	} else if len(msg) > 7 && msg[:7] == "rename|" {
		newName := strings.Split(msg, "|")[1]
		//判断name是否存在
		_, ok := u.server.OnlineMap[newName]
		if ok {
			u.SendMsg("Rename ERR!!!\n")
		} else {
			u.server.mapLock.Lock()
			delete(u.server.OnlineMap, u.Name)
			u.server.OnlineMap[newName] = u
			u.server.mapLock.Unlock()
			u.Name = newName
			u.SendMsg("Rename SUCCESS!!!:" + u.Name + "\n")
		}
	} else if len(msg) > 4 && msg[:3] == "to|" {
		//获取对方用户名
		remoteName := strings.Split(msg, "|")[1]
		if remoteName == "" {
			u.SendMsg("RemoteName ERR!!!\n")
			return
		}
		//根据用户名得到对方的User对象
		remoteUser, ok := u.server.OnlineMap[remoteName]
		if !ok {
			u.SendMsg("RemoteUser ERR!!!\n")
			return
		}
		//获取消息内容 通过对方的user对象发送过去
		content := strings.Split(msg, "|")[2]
		if content == "" {
			u.SendMsg("Msg ERR!!!\n")
			return
		}
		remoteUser.SendMsg(u.Name + " SAY:" + content + "\n")

	} else {
		u.server.BroadCast(u, msg)
	}
}

//给当前User对应的客户端发送消息
func (u *User) SendMsg(msg string) {
	u.conn.Write([]byte(msg))
}
